package com.acmen.ump.core.aop;

import com.acmen.ump.core.dto.ApiResponse;
import com.acmen.ump.core.dto.ApiResponseErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Acmen
 * @ClassName ApiResponseAop.java
 * @Description 处理响应结果，如果响应结果不为ApiResponse类型，则进行封装
 * @CreateTime 2019年08月28日 23:49:30
 */
@Slf4j
@Aspect
@Order(5)
@Component
public class ApiResponseAop {

    /**
     * 切点
     */
    @Pointcut("execution(public * com.acmen.ump.*.controller..*(..))")
    public void httpApiResponse() {
    }

    /**
     * 环切
     */
    @Around("httpApiResponse()")
    public ApiResponse handlerController(ProceedingJoinPoint proceedingJoinPoint) {
        ApiResponse apiResponse = null;
        try {
            //获取方法的执行结果
            Object proceed = proceedingJoinPoint.proceed();
            if (proceed instanceof ApiResponse) {
                apiResponse = (ApiResponse) proceed;
            } else {
                apiResponse = new ApiResponse(proceed);
            }
        }  catch (Throwable throwable) {
            apiResponse = new ApiResponse(ApiResponseErrorCode.CODE_999);
        }
        return apiResponse;
    }
}
